/**
 * 
 */
package com.tpl.core.basedata.action.sys;

import java.util.ArrayList;
import java.util.List;

import com.tpl.core.JsonUtil;
import com.tpl.core.action.BaseAction;
import com.tpl.core.basedata.common.constant.ICacheConstants;
import com.tpl.core.basedata.service.DeptUserService;
import com.tpl.core.basedata.service.RoleService;
import com.tpl.core.basedata.service.RoleUserService;
import com.tpl.core.common.page.Page;
import com.tpl.core.common.redis.RedisClientUtil;
import com.tpl.core.entity.sys.Role;
import com.tpl.core.entity.sys.User;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * @author CrazyLee
 * RoleUserAction.java
 * 2016年7月30日
 */
@Controller
@RequestMapping("/roleUser")
public class RoleUserAction extends BaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 2699671553163630335L;
	@Autowired
	private DeptUserService deptUserService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private RoleUserService roleUserService;
	
	@RequestMapping("/toRoleUserManage.do")
	public String toRoleUserManage(){
		return "role/roleUserManage";
	}
	@RequestMapping("/toRoleUser.do")
	public String toRoleUserList(){
		return "role/roleUser_list";
	}
	
	@RequestMapping("/toRoleUser_role.do")
	public String toRoleUser_role(Long deptId){
		Page page=null;
		List<User> users = new ArrayList<User>();
		if(deptId!=null){
			users = deptUserService.getUserByDeptId(deptId);
			page = roleService.getRolePage(deptId, getPageIndex(), getPageSize());
		}
		putInRequest("list", users,"page",page,"deptId",deptId);
		
		return "role/roleReUserlist";
	}
	
	@RequestMapping("/getUserByRole.do")
	public @ResponseBody void getUserByRole(Long roleId){
		List<Role> list = roleService.getRoleUserByParam(null, roleId);
		JSONArray ja= JsonUtil.toJSONArray(list);
		outJsonSuccess(ja.toString());
	}
	
	@RequestMapping("/saveRoleUser.do")
	public @ResponseBody void saveRoleUser(Long[] del_,Long[] new_,Long roleId){
		roleUserService.saveRoleUser(new_, del_, roleId);
		Role role=roleService.getRoleById(roleId);
		Long deptId=role.getDeptId();
		if(del_!=null)
			for(Long userId : del_)
				clearCache(userId, deptId);
		if(new_!=null)
			for(Long userId : new_)
				clearCache(userId, deptId);
		outJsonSuccess();
	}
	/**
	 * 清除缓存
	 */
	private void clearCache(Long userId,Long deptId){
		RedisClientUtil.delkeyObject(ICacheConstants.CACHE_AUTH_USER_ROLE+deptId+"#"+userId);
	}
	
}
